package com.jstyle.beatecg.activity;

import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.jstyle.beatecg.R;

import com.jstyle.beatecg.ble.BleManager;
import com.jstyle.beatecg.ble.BleService;
import com.jstyle.beatecg.fragment.ActivityFragment;
import com.jstyle.beatecg.fragment.TrackFragment;
import com.jstyle.beatecg.model.BleData;
import com.jstyle.beatecg.util.DateUtil;
import com.jstyle.beatecg.util.ImageUtils;
import com.jstyle.beatecg.util.ResolveData;
import com.jstyle.beatecg.util.RxBus;
import com.jstyle.beatecg.util.SendData;
import com.jstyle.beatecg.util.SharePreferenceUtils;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class ActivitySportActivity extends AppCompatActivity {
    private static final String TAG = "ActivitySportActivity";

    @BindView(R.id.rg_user_change_language)
    RadioGroup rgUserChangeLanguage;
    @BindView(R.id.bt_pause)
    Button btPause;
    @BindView(R.id.bt_stop)
    Button btStop;
    //    @BindView(R.id.viewPager_sport)
//    ViewPager viewPagerSport;
    @BindView(R.id.rb_activity)
    RadioButton rbActivity;
    @BindView(R.id.rb_track)
    RadioButton rbTrack;
    @BindView(R.id.look)
    ImageView look;
    @BindView(R.id.main_framelayout)
    FrameLayout main_framelayout;


    private FragmentManager fragmentManager;
    ActivityFragment activityFragment;
    TrackFragment trackFragment;
    private final static int FRAGMENT_SPORT = 0;
    private final static int FRAGMENT_track = 1;
    private int showFragment;
    private Disposable disposable;
    private int countTime;
    private Disposable subscription;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sport);
        ButterKnife.bind(this);
        fragmentManager = getSupportFragmentManager();
        //  startTransaction(FRAGMENT_SPORT);
        rgUserChangeLanguage.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                Log.i(TAG, "onCheckedChanged: ");
                if (checkedId == R.id.rb_track) {
                    //  viewPagerSport.setCurrentItem(1);

                    startTransaction(FRAGMENT_track);
                } else if (checkedId == R.id.rb_activity) {
                    // viewPagerSport.setCurrentItem(0);
                    startTransaction(FRAGMENT_SPORT);
                }
            }
        });
        activityFragment = new ActivityFragment();
        trackFragment = new TrackFragment();
        trackFragment.settype(getIntent().getStringExtra("type"));
        rbActivity.setText(getIntent().getStringExtra("type"));
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.main_framelayout, trackFragment);
        fragmentTransaction.add(R.id.main_framelayout, activityFragment);
        fragmentTransaction.commit();
        startCount();
        initData();
        startTransaction(FRAGMENT_SPORT);

        if(null==SharePreferenceUtils.getSpString(SharePreferenceUtils.KEY_map)){
            SharePreferenceUtils.setSpString(SharePreferenceUtils.KEY_map,"0");
        }
        if("0".equals(SharePreferenceUtils.getSpString(SharePreferenceUtils.KEY_map))){
            look.setImageDrawable(this.getResources().getDrawable(R.drawable.turn_on));
            lookED=true;
            //trackFragment.Viewstatus(0);
        }else{
            lookED=false;
            look.setImageDrawable(this.getResources().getDrawable(R.drawable.turn_off));
           // trackFragment.Viewstatus(1);
        }

    }

    private void initData() {
        BleManager.getInstance().offerValue(SendData.enableTest());
        BleManager.getInstance().offerValue(SendData.enableActivityHeart(true));
        BleManager.getInstance().offerValue(SendData.enableActivity(true));
        BleManager.getInstance().writeValue();
        subscription = RxBus.getInstance().toObservable(BleData.class).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<BleData>() {
            @Override
            public void accept(BleData data) throws Exception {
                String action = data.getAction();
               if (BleService.ACTION_DATA_AVAILABLE.equals(action)) {
                    resolveData(data.getValue());
                }
            }


        });
    }



    private void resolveData(byte[] value) {
        switch (value[0]) {
            case SendData.CMD_ENABLE_ACTIVITY:
                updateActivityData(value);
                break;
            case SendData.CMD_ENABLE_ACTIVITY_HEART:
                updateHeartRateData(value);
                break;
        }
    }

    private void updateHeartRateData(byte[] value) {
        float heartRate = ResolveData.getValue(value[1],0);
        activityFragment.updateHeartRate(heartRate);
        String MYheartRate="";
        if((heartRate+"").contains(".")){
            String s = String.valueOf(heartRate);
            MYheartRate = s.substring(0, s.indexOf("."));
        }else{
            MYheartRate=heartRate+"";
        }
        trackFragment.updateHeartRate(MYheartRate);
    }
    private int tempSteps;
    int maxCount=10;
    private LinkedList<Integer>stepList=new LinkedList<>();
    private void updateActivityData(byte[]value) {

        int steps = ResolveData.getValue(value[1], 2)
                + ResolveData.getValue(value[2], 1)
                + ResolveData.getValue(value[3], 0);
        tempSteps=steps;
        int cal = ResolveData.getValue(value[7], 2)
                + ResolveData.getValue(value[8], 1)
                + ResolveData.getValue(value[9], 0);
        int distance = ResolveData.getValue(value[10], 2)
                + ResolveData.getValue(value[11], 1)
                + ResolveData.getValue(value[12], 0);
        activityFragment.updateActivityData(cal / 100f, distance);
        trackFragment.updateActivityData(cal / 100f, distance);

    }

    protected void startTransaction(int fragmentId) {
        showFragment = fragmentId;
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        hideFragment(fragmentTransaction);
        switch (fragmentId) {
            case FRAGMENT_SPORT:
                if (activityFragment == null) {

                } else {
                    fragmentTransaction.show(activityFragment);
                }
                look.setVisibility(View.GONE);
                //ImageUtils.setMargins(main_framelayout,0,51,0,0);
                break;
            case FRAGMENT_track:
                if (trackFragment == null) {

                } else {
                    fragmentTransaction.show(trackFragment);
                }
                look.setVisibility(View.VISIBLE);
               // ImageUtils.setMargins(main_framelayout,0,0,0,0);
                break;
        }

        fragmentTransaction.commit();
    }

    private void hideFragment(FragmentTransaction fragmentTransaction) {
        hideFragment(activityFragment, fragmentTransaction);
        hideFragment(trackFragment, fragmentTransaction);
    }

    private void hideFragment(Fragment fragment, FragmentTransaction transaction) {
        if (fragment != null) {
            transaction.hide(fragment);
        }
    }

    boolean enable = true;
    boolean lookED=true;
    @OnClick({R.id.bt_pause, R.id.bt_stop,R.id.look})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_pause:
                enable = !enable;
                btPause.setBackgroundResource(enable ? R.drawable.sport_pause : R.drawable.sport_start);
                startCount();
                break;
            case R.id.bt_stop:
                trackFragment.stop();
                BleData bleData = new BleData();
                bleData.setAction("up_history");//更新运动历史记录
                RxBus.getInstance().post(bleData);
                break;
            case R.id.look:
              if(lookED){
                  lookED=false;
                  look.setImageDrawable(this.getResources().getDrawable(R.drawable.turn_off));
                  trackFragment.Viewstatus(1);
                  SharePreferenceUtils.setSpString(SharePreferenceUtils.KEY_map,"1");
              }else{
                  look.setImageDrawable(this.getResources().getDrawable(R.drawable.turn_on));
                  lookED=true;
                  trackFragment.Viewstatus(0);
                  SharePreferenceUtils.setSpString(SharePreferenceUtils.KEY_map,"0");
              }
                break;
        }
    }

    private void addSteps(){
        if(tempSteps==0)return;
        if(stepList.size()==10)stepList.poll();
        stepList.add(tempSteps);
    }
    public void startCount() {
        if (enable) {
            Observable.interval(0, 1, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {
                @Override
                public void onSubscribe(Disposable d) {
                    disposable = d;
                }

                @Override
                public void onNext(Long value) {
                    countTime++;
                    addSteps();
                    if(countTime>=10){
                        showSpeeds();
                        String time = DateUtil.getActivityTime(countTime);
                        activityFragment.updateTime(time);
                        trackFragment.updateTime(time);
                    }

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });
        } else {
            disposable.dispose();
        }

    }

    private void showSpeeds() {
        if(stepList.size()==0)return;
        float speed=(stepList.get(stepList.size()-1)-stepList.get(0))*0.252f;
        activityFragment.updateSpeed(speed<0?0:speed);
        trackFragment.updateSpeed(speed<0?0:speed);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unsubscribe(disposable);
        unsubscribe(subscription);
        BleManager.getInstance().offerValue(SendData.enableActivity(false));
        BleManager.getInstance().offerValue(SendData.enableActivityHeart(false));
    }

    private void unsubscribe(Disposable disposable) {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }
}
